<template>
  <el-dialog
    :model-value="props.visible"
    title="设置角色路由对话框"
    width="90%"
    :lock-scroll="false"
    :close-on-click-modal="false"
    :before-close="closeDialog"
    @open="openDialogHandler"
  >
    <div style="min-height: 50vh">
      <div class="infoBar">
        <div class="title">当前角色信息</div>
        <div class="form">
          <div class="infoItem">
            <div class="label">角色编码 :</div>
            <div class="value">{{ roleName }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色描述 :</div>
            <div class="value">{{ roleDescription }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色名称 :</div>
            <div class="value">{{ roleRealName }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色分类 :</div>
            <div class="value">{{ getDescriptionStr(parentSortIds) }}</div>
          </div>
        </div>
      </div>

      <TableCard operation-bar-label="批量管理角色路由">
        <template #operationBar>
          <el-popconfirm
            title="确认批量删除角色路由？"
            placement="right"
            @confirm="setRoleRoutes('remove', multipleDeleteItems)"
          >
            <template #reference>
              <el-button v-once-click color="#F56C6C" plain size="small">
                批量删除路由
              </el-button>
            </template>
          </el-popconfirm>
        </template>

        <template #table>
          <el-table
            :data="roleRoutesList"
            stripe
            row-key="id"
            size="small"
            :default-expand-all="true"
            style="width: 100%"
            max-height="300"
            @selection-change="deleteItemSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="enable" label="enable" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column property="name" label="Name" width="160" />
            <el-table-column property="path" label="Path" min-width="260" />
            <el-table-column label="Sort" min-width="260" show-overflow-tooltip>
              <template #default="scope">
                {{
                  getDescriptionStr(
                    findParentValues(sortTree, scope.row?.sortId)
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              property="description"
              label="Description"
              min-width="260"
            />
            <el-table-column label="operation" width="100" fixed="right">
              <template #default="scope">
                <el-popconfirm
                  title="确认删除角色路由？"
                  placement="left"
                  @confirm="setRoleRoutes('remove', [scope.row.id])"
                >
                  <template #reference>
                    <el-button v-once-click color="#F56C6C" plain size="small">
                      删除路由
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>

      <br />

      <TableCard operation-bar-label="批量设置角色路由">
        <template #operationBar>
          <el-button
            v-once-click
            color="#626aef"
            plain
            size="small"
            @click="setRoleRoutes('add', multipleSelectionItems)"
          >
            添加
          </el-button>

          <el-popconfirm
            title="确认重置当前角色路由？"
            placement="right"
            @confirm="setRoleRoutes('refresh', multipleSelectionItems)"
          >
            <template #reference>
              <el-button v-once-click type="info" size="small">
                重置
              </el-button>
            </template>
          </el-popconfirm>
        </template>

        <template #table>
          <el-table
            ref="multipleTableRef"
            :data="queryRouteList"
            stripe
            row-key="id"
            size="small"
            :default-expand-all="true"
            style="width: 100%"
            max-height="300"
            @selection-change="handleSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="enable" label="enable" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column property="name" label="Name" sortable width="160">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 6px">{{ scope.row.name }}</div>
                  <el-icon
                    v-if="scope.row.isRedirect == 0"
                    title="上级重定向路由"
                    color="#eebe77"
                    size="17"
                  >
                    <InfoFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="path" label="Path" min-width="260" />
            <el-table-column label="Sort" min-width="260" show-overflow-tooltip>
              <template #default="scope">
                {{
                  getDescriptionStr(
                    findParentValues(sortTree, scope.row?.sortId)
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              property="description"
              label="Description"
              min-width="260"
            />
            <el-table-column label="operation" width="100" fixed="right">
              <template #default="scope">
                <!-- <el-tag  type="danger">
                  已添加
                </el-tag> -->
                <el-button
                  v-if="!hasRoute(scope.row.id)"
                  v-once-click
                  color="#626aef"
                  plain
                  size="small"
                  @click="setRoleRoutes('add', [scope.row.id])"
                >
                  添加路由
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button color="#626aef" size="large" @click="closeDialog">
          关闭弹窗
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import { getAllSortRoutesApi } from '@/request/api/routes'
import {
  getRoleRoutesDetailApi,
  setRoleRoutesApi,
} from '@/request/api/roleRoutes'

import TableCard from '@/components/TableCard/TableCard.vue'

const props = defineProps({
  roleInfo: { type: Object as () => RoleItf, default: {} },
  visible: { type: Boolean, default: false },
})

// 定义传递给父组件的方法
const emits = defineEmits(['closeDialogHandler'])
const closeDialog = () => emits('closeDialogHandler')

const { originData, sortTree } = storeToRefs(useSortTreeStore())
const { findParentValues, getSortList, getDescriptionStr } = useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()
const { openAlert } = useMessageAlertStore()

// 对话框显示时的回调
const openDialogHandler = () => {
  if (originData.value.length === 0) getSortList()

  const { name, realName, description, sortId } = props.roleInfo
  roleName.value = name
  roleRealName.value = realName
  roleDescription.value = description
  parentSortIds.value = findParentValues(sortTree.value, sortId)

  getRoutesList()
  getRoleRoutesDetail()
}

// 角色上级分类id列表
const parentSortIds = ref<string[]>([])
const roleName = ref<string>('')
const roleRealName = ref<string>('')
const roleDescription = ref<string>('')

// 多选路由删除选项
const multipleDeleteItems = ref<string[]>([])
const deleteItemSelectionChange = (val: RouteItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleDeleteItems.value = ids
}

// 角色路由列表
const roleRoutesList = ref<RouteItf[]>([])
// 获取角色路由详情
const getRoleRoutesDetail = async () => {
  const res = await getRoleRoutesDetailApi(props.roleInfo.id)
  if (res.code !== 200) return openAlert.error(res.message)
  roleRoutesList.value = res.data || []
}

// 判断角色是否已经拥有某个路由
const hasRoute = (id: string): boolean => {
  if (roleRoutesList.value.length === 0) return false
  return roleRoutesList.value.some((item) => item.id === id)
}

// 查询到的路由列表
const queryRouteList = ref<RouteItf[]>([])
// 获取当前角色可以使用的路由列表
const getRoutesList = async () => {
  // 以角色分类的根分类id作为查询条件
  let sortId = parentSortIds.value[0] || ''

  const res = await getAllSortRoutesApi(sortId)
  if (res.code !== 200) return openAlert.error(res.message)

  let dataMap = {}
  res.data.forEach((item) => {
    const parentId = item.parentId || 'null'
    dataMap[parentId] = dataMap[parentId] || []
    dataMap[parentId].push(item)
  })
  queryRouteList.value = buildTree(dataMap)

  function buildTree(data, parentId = null) {
    const tree = []
    const children = data[parentId] || []
    children.forEach((child) => {
      const subtree = buildTree(data, child.id)
      if (subtree.length > 0) child.children = subtree
      tree.push(child)
    })
    return tree
  }
}

// 多选表格对象
const multipleTableRef = ref<any>()
// 多选路由选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 为角色设置权限
const setRoleRoutes = async (
  type: 'refresh' | 'add' | 'remove',
  ids: string[]
) => {
  const res = await setRoleRoutesApi(props.roleInfo.id, type, ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('角色设置路由成功！')
  getRoleRoutesDetail()
  multipleTableRef.value!.clearSelection()
}
</script>

<style lang="less" scoped>
.label {
  font-size: 15px;
  font-weight: bold;
  color: #606266;
  padding-right: 14px;
  user-select: none;
}

.infoBar {
  padding: 10px;

  > .title {
    font-size: 14px;
    font-weight: bold;
    user-select: none;
    color: #606266;
    letter-spacing: 2px;
    padding-bottom: 5px;
  }

  > .form {
    display: flex;
    flex-wrap: wrap;

    > .infoItem {
      display: flex;
      align-items: center;
      min-width: 400px;
      padding: 5px 0;

      > .label {
        font-size: 14px;
        font-weight: bold;
        padding-right: 15px;
        user-select: none;
        color: #918f8f;
        letter-spacing: 2px;
        width: 80px;
      }

      > .value {
        font-size: 14px;
        font-weight: bold;
        color: #606266;
        letter-spacing: 1px;
      }
    }
  }
}
</style>
